package day04;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import util.CookieUtil;

import java.io.IOException;

@WebServlet("/showLogin")
public class ShowLoginServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("ShowLoginServlet.service()");

        String username= CookieUtil.findCookie("username",request);
        String password= CookieUtil.findCookie("password",request);

        //使用cookie中的用户名和密码自动登录
        if("abc".equals(username)&&"123".equals(password)){
            //自动登录成功

            //刷新cookie存活时间
            CookieUtil.addCookie("username",username,response);
            CookieUtil.addCookie("password",password,response);

            response.sendRedirect(request.getContextPath()+"/success.jsp");
            return;
        }

        //以前登录过，但cookie有效期间，在其他机器上修改过密码
        CookieUtil.removeCookie("username",response);
        CookieUtil.removeCookie("password",response);

        request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request,response);
    }
}
